/*******************************************************************************
 * (c) Copyright 2017 lvxi. All Rights Reserved.
 ******************************************************************************/

package edu.jxufe.nb112.blog.admin.web.support;

import edu.jxufe.nb112.blog.core.persist.entity.SysConfig;
import edu.jxufe.nb112.blog.core.persist.service.user.SysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;

/**
 * Created by lvxi on 2017/3/19.
 * Note: 系统启动时读取配置支持
 */
public class SystemConfigSupport implements ServletContextListener {
    private static final Logger LOG = LoggerFactory.getLogger(SystemConfigSupport.class.getName());
    /**
     * 容器启动
     * @param servletContextEvent
     */
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        LOG.info("系统启动中");
        ServletContext servletContext =servletContextEvent.getServletContext();
        String contextPath = servletContext.getContextPath();
        servletContext.setAttribute("ctx",contextPath);

        ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        servletContext.setAttribute("springctx",applicationContext);

        LOG.info("读取系统配置...");
        SysConfigService sysConfigService = applicationContext.getBean(SysConfigService.class);
        List<SysConfig> sysConfigs = sysConfigService.loadSystemModuleConfig();
        for(SysConfig sysConfig : sysConfigs){
            //以_开头session中的值为系统配置
            String key = "_"+sysConfig.getModule()+"_"+sysConfig.getKeyName();
            Object value = sysConfigService.newInstanceSysConfigValue(sysConfig);
            servletContext.setAttribute(key,value);
            if(LOG.isDebugEnabled()){
                LOG.debug("{}={}",key,value);
            }
        }
    }

    /**
     * 容器关闭
     * @param servletContextEvent
     */
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        LOG.info("系统关闭");
    }
}
